<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>js闭包之应用场景示例(数组排序)</title>
</head>
<body>
  <script>
    const cart = [
      { name: 'iphone', price: 8000 },
      { name: 'imac', price: 12000 },
      { name: 'ipad', price: 3688 }
    ]
    const order = function (field, direction = 'asc') {
      return function(a, b) {
        const res = direction === 'asc' ? a[field] > b[field] : a[field] < b[field]
        return res ? 1 : -1
      }
    }
    console.table(cart.sort(order('price')))
    console.table(cart.sort(order('price', 'desc')))
  </script>
</body>
</html>